package cn.glow.readingcloud.homepage.service.impl;


import cn.glow.readingcloud.common.utils.CommonUtil;
import cn.glow.readingcloud.homepage.dao.IndexBannerItemMapper;
import cn.glow.readingcloud.homepage.dao.IndexBannerMapper;
import cn.glow.readingcloud.homepage.dto.IndexBannerDto;
import cn.glow.readingcloud.homepage.dto.IndexBannerItemView;
import cn.glow.readingcloud.homepage.pojo.IndexBanner;
import cn.glow.readingcloud.homepage.pojo.IndexBannerItem;
import cn.glow.readingcloud.homepage.service.IndexBannerService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author Glow
 * @Date 2023-04-21 16:25:21
 * @Description
 * @Version 1.0
 */
@Service
public class IndexBannerServiceImpl extends ServiceImpl<IndexBannerMapper, IndexBanner> implements IndexBannerService {


    @Autowired
    private IndexBannerMapper indexBannerMapper;
    @Autowired
    private IndexBannerItemMapper indexBannerItemMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public IndexBannerDto getBannerVO(Integer bannerId) {
        IndexBannerDto indexBannerDto =(IndexBannerDto) redisTemplate.opsForValue().get("homepageBannerID:"+bannerId);
        if( indexBannerDto != null)
        {
            return indexBannerDto;
        }
        IndexBanner indexBanner = indexBannerMapper.selectById(bannerId);
        if (indexBanner == null) {
            return null;
        }

        // DB查询Banner明细
        LambdaQueryWrapper<IndexBannerItem> queryWrapper =  new LambdaQueryWrapper<>();
        queryWrapper.eq(IndexBannerItem::getBannerId,bannerId);
        List<IndexBannerItem> bannerItems = indexBannerItemMapper.selectList(queryWrapper);
        if (CommonUtil.isEmpty(bannerItems)) {
            return null;
        }

        List<IndexBannerItemView> items = new ArrayList<>();
        for (int i = 0; i < bannerItems.size(); i++) {
            IndexBannerItemView item = new IndexBannerItemView();
            IndexBannerItem banner = bannerItems.get(i);
            BeanUtils.copyProperties(banner, item);
            items.add(item);
        }
        indexBannerDto = new IndexBannerDto(indexBanner.getId(), indexBanner.getName(), items);
        redisTemplate.opsForValue().set("homepageBannerID:"+bannerId,indexBannerDto);
        return indexBannerDto;
    }
}
